clear all;
close all;

%  =======================================================================================================================================================
% 
%  Code Description: 
%  This codefile generates result as provided in section 3 and in internet appendix D. 
% 
%  =======================================================================================================================================================
% 
%  Major output:
%  Figure 3: Cross-fund holdings in Germany in December 2019
%  Figure IA.6: Cross-fund holdings in Germany in December 2019.
%  =======================================================================================================================================================
% 
%  General disclaimer:
%  This file directory produces replication code for "Connected Funds". 
%  Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources, 
%  we have included pseudo data to show how the raw data are formatted. 
%  Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
% 
%  =======================================================================================================================================================

% Add functions folders
projectpath = 'C:\ConnectedFunds_Codebase\'
addpath(strcat(projectpath, 'Code\matlab_functions'))

%%% Holdings (end of Dec 2019)
load(strcat(projectpath, 'Data\IFS\mat\IFS_Holdings_201912.mat'))
IFS_Holdings_1     = IFS_Holdings;
IFS_Holdings_1(IFS_Holdings_1.AMOUNT<=0,:) = [];
IFS_Holdings_IF_1  = IFS_Holdings_1(startsWith(IFS_Holdings_1.ESA2010,'S_124'),:);

%%% Holdings (end of Jan 2020)
load(strcat(projectpath, 'Data\IFS\mat\IFS_Holdings_202001.mat'))
IFS_Holdings_2     = IFS_Holdings;
IFS_Holdings_2(IFS_Holdings_2.AMOUNT<=0,:) = [];
IFS_Holdings_IF_2  = IFS_Holdings_2(startsWith(IFS_Holdings_2.ESA2010,'S_124'),:);

clear IFS_Holdings

%%%%%% trading activity

ufund1 = unique(IFS_Holdings_IF_1.ISIN);
ufund2 = unique(IFS_Holdings_IF_2.ISIN);

ufund = intersect(ufund1,ufund2);
clear ufund1 ufund2

[~,idx1] = ismember(IFS_Holdings_IF_1.SECCODE,ufund);
[~,idx2] = ismember(IFS_Holdings_IF_2.SECCODE,ufund);

IFS_Holdings_IF_1(idx1==0,:) = [];
IFS_Holdings_IF_2(idx2==0,:) = [];
clear idx* 

% holdings of German fund shares

[~,idx1] = ismember(IFS_Holdings_IF_1.ISIN,ufund);
[~,idx2] = ismember(IFS_Holdings_IF_2.ISIN,ufund);
IFS_Holdings_IF_1(idx1==0,:); 
IFS_Holdings_IF_2(idx2==0,:);
clear idx* 

[~,idx1] = ismember(IFS_Holdings_IF_1.ISIN,ufund);
[~,idx2] = ismember(IFS_Holdings_IF_2.ISIN,ufund);

IFS_Holdings_IF_1(idx1==0,:) = [];
IFS_Holdings_IF_2(idx2==0,:) = [];
clear idx* 

%%% generate portfolio matrices 
[~,idx1] = ismember(IFS_Holdings_IF_1.ISIN,ufund);
[~,idx2] = ismember(IFS_Holdings_IF_1.SECCODE,ufund);
Network1        = accumarray([idx1 idx2],IFS_Holdings_IF_1.SECNOMUN,[length(ufund) length(ufund)]);
Network1_AMOUNT = accumarray([idx1 idx2],IFS_Holdings_IF_1.AMOUNT,[length(ufund) length(ufund)]);

[~,idx1] = ismember(IFS_Holdings_IF_2.ISIN,ufund);
[~,idx2] = ismember(IFS_Holdings_IF_2.SECCODE,ufund);
Network2 = accumarray([idx1 idx2],IFS_Holdings_IF_2.SECNOMUN,[length(ufund) length(ufund)]);
Network2_AMOUNT = accumarray([idx1 idx2],IFS_Holdings_IF_2.AMOUNT,[length(ufund) length(ufund)]);

clear idx*

ufund_IF = ufund;

% add info on funds (incl. flows)
load(strcat(projectpath, 'Data\IFS\IFS_All_CleanData'));

IFS_All = IFS_All(IFS_All.DATUM==201912,:);
[~,idx] = ismember(ufund_IF,IFS_All.ISIN);

IFS = IFS_All(idx,:);
clear umonth ufund;

clear IFS_All;

% more descriptives
fund_type = IFS.artmittel;

S_Net = zeros(5,5);
for i = 1:3
for j = 1:3
    S_Net(i,j) = sum(vect(Network1_AMOUNT(fund_type==i,fund_type==j)));  
    S_Net(i,4) = sum(vect(Network1_AMOUNT(fund_type==i,fund_type==7)));
    S_Net(4,i) = sum(vect(Network1_AMOUNT(fund_type==7,fund_type==i)));
end

S_Net(i,5) = sum(vect(Network1_AMOUNT(fund_type==i,:))) - sum(S_Net(i,:));
end
S_Net(4,4) = sum(vect(Network1_AMOUNT(fund_type==7,fund_type==7)));
S_Net(4,5) = sum(vect(Network1_AMOUNT(fund_type==7,:))) - sum(S_Net(4,:));
S_Net(5,5) = sum(Network1_AMOUNT(:)) - sum(S_Net(:));
S_Net = (1000*10^-9).*S_Net;

close

imagesc(S_Net(1:4,1:4));
set(gca, 'XTick',(1:4), 'XTickLabel',{'equity' 'bond' 'mixed' 'FoF' })                         
set(gca, 'YTick',(1:4), 'YTickLabel',{'equity' 'bond' 'mixed' 'FoF'  }) 
ylabel('type x'); xlabel('type y');
myColorMap = jet(256);
myColorMap(1,:) = 1;
myColorMap(2:80,:) = [];
myColorMap(end-20:end,:) = []; 
colormap(myColorMap);
colorbar; 
textStrings = num2str(vect(S_Net(1:4,1:4)), '%0.2f');       % Create strings from the matrix values
textStrings = strtrim(cellstr(textStrings));                % Remove any space padding
[x, y] = meshgrid(1:4);                                     % Create x and y coordinates for the strings
hStrings = text(x(:), y(:), textStrings(:), ...             % Plot the strings
                'HorizontalAlignment', 'center');
title('Cross-Holdings Network (x invests in y)');
yline(1.5); yline(2.5); yline(3.5); 
xline(1.5); xline(2.5); xline(3.5); 
saveas(gcf, strcat(projectpath, 'Paper\Figures\Fig3L_Cross-fund holdings in Germany in December 2019.png'),'png');

%%% UCITS vs AIF
fund_ucits = double(IFS.UCITSAIF<200);

S_Net = [];
S_Net(1,1) = sum(vect(Network1_AMOUNT(fund_ucits==1,fund_ucits==1)));
S_Net(1,2) = sum(vect(Network1_AMOUNT(fund_ucits==1,fund_ucits==0)));
S_Net(2,1) = sum(vect(Network1_AMOUNT(fund_ucits==0,fund_ucits==1)));
S_Net(2,2) = sum(vect(Network1_AMOUNT(fund_ucits==0,fund_ucits==0)));
S_Net = (1000*10^-9).*S_Net;


close
imagesc(S_Net); 
set(gca, 'XTick',(1:2), 'XTickLabel',{'Retail' 'Inst.'})                         
set(gca, 'YTick',(1:2), 'YTickLabel',{'Retail' 'Inst.'}) 
ylabel('category x'); xlabel('category y');
myColorMap = jet(256);
myColorMap(1,:) = 1;
myColorMap(2:80,:) = [];
myColorMap(end-20:end,:) = []; 
colormap(myColorMap);
colorbar
textStrings = num2str(S_Net(:), '%0.2f');       % Create strings from the matrix values
textStrings = strtrim(cellstr(textStrings));    % Remove any space padding
[x, y] = meshgrid(1:2);                         % Create x and y coordinates for the strings
hStrings = text(x(:), y(:), textStrings(:), ... % Plot the strings
                'HorizontalAlignment', 'center');
% title('Cross-Holdings Network (x invests in y)');
yline(1.5); 
xline(1.5);
saveas(gcf, strcat(projectpath, 'Paper\Figures\Fig3R_Cross-fund holdings in Germany in December 2019.png'),'png');

S_Net(2,2) ./ sum(S_Net(:))

%%% Figure IA.6: Cross-fund holdings in Germany in December 2019 (by artmittel and typ_invv)
a = [1 1;
 2 1;
 3 1;
 7 1;
 1 0;
 2 0;
 3 0;
 7 0];

S_Net = zeros(length(a),length(a));
for i = 1:length(a)
for j = 1:length(a)
    S_Net(i,j) = sum(vect(Network1_AMOUNT(fund_type==a(i,1) & fund_ucits==a(i,2),fund_type==a(j,1) & fund_ucits==a(j,2))));  
end
end
S_Net = (1000*10^-9).*S_Net;

close
imagesc(S_Net); 
set(gca, 'XTick',(1:length(a)), 'XTickLabel',{'Equity-Retail' 'Bond-Retail' 'Mixed-Retail' 'FoF-Retail' 'Equity-Inst.' 'Bond-Inst.'  'Mixed-Inst.'  'FoF-Inst.'})                         % Label Ticks
set(gca, 'YTick',(1:length(a)), 'YTickLabel',{'Equity-Retail' 'Bond-Retail' 'Mixed-Retail' 'FoF-Retail' 'Equity-Inst.' 'Bond-Inst.'  'Mixed-Inst.'  'FoF-Inst.'}) 
ylabel('category x'); xlabel('category y');
xtickangle(45);
myColorMap = jet(256);
myColorMap(1,:) = 1;
myColorMap(2:80,:) = [];
myColorMap(end-20:end,:) = []; 
colormap(myColorMap); 
colorbar
textStrings = num2str(S_Net(:), '%0.2f');       % Create strings from the matrix values
textStrings = strtrim(cellstr(textStrings));    % Remove any space padding
[x, y] = meshgrid(1:length(a));                 % Create x and y coordinates for the strings
hStrings = text(x(:), y(:), textStrings(:), ... % Plot the strings
                'HorizontalAlignment', 'center');
% title('Cross-Holdings Network (x invests in y)');
yline(1.5); yline(2.5); yline(3.5); yline(4.5); yline(5.5); yline(6.5); yline(7.5);
xline(1.5); xline(2.5); xline(3.5); xline(4.5); xline(5.5); xline(6.5); xline(7.5);
saveas(gcf, strcat(projectpath, 'Paper\Figures\FigIA6_Cross-fund holdings in Germany in December 2019.png'),'png');